package com.ymk.cmd;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.ymk.base.cmd.ACmd;
import com.ymk.base.cmd.CmdSign;
import com.ymk.base.exception.MallException;
import com.ymk.base.service.WxService;

import com.ymk.base.utlis.DateUtil;
import com.ymk.base.utlis.ParamsBuilder;
import com.ymk.bo.user.PayPaymentBO;
import com.ymk.bo.user.UserInfoBO;
import com.ymk.core.code.cmd.UserCmdCode;
import com.ymk.core.constants.SysConstants;
import com.ymk.core.constants.WxConstants;
import com.ymk.core.enums.orders.OrdersItemStatusEnum;
import com.ymk.service.IPayPaymentService;
import com.ymk.service.IUserInfoService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class UserGetMoneyCmd extends ACmd {

    private final static Logger logger = LoggerFactory.getLogger(UserGetMoneyCmd.class);
    @Override
    public CmdSign executeSop(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        UserInfoBO reqData = super.getData(sign, UserInfoBO.class);

        //根据用户id查询用户信息
        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("userId", reqData.getUserId());
        UserInfoBO userInfoBO = userService.get(paramsBuilder.build());
        sign.setUserId(Integer.valueOf(userInfoBO.getId()));
        //比较金额
        if (userInfoBO.getAmount().compareTo(reqData.getAmount()) == -1){
            throw new MallException("余额不足。");
        }
        //发起提现
        int total = reqData.getAmount().multiply(new BigDecimal("100")).intValue();
        String amount = String.valueOf(total);
        paramsBuilder.clearParam().addParam("openid",userInfoBO.getWxOpenId())
                .addParam("amount",amount);
        String resData = HttpUtil.post(WxConstants.WX_PAY,JSON.toJSONString(paramsBuilder.build()));
        JSONObject json = JSON.parseObject(resData);
        logger.info("提现结果===="+json.toJSONString());
        if ((int)json.get("code") == 500){
            //发送提现失败通知
            sendFailMessage(userInfoBO,reqData);
            throw new MallException("提现失败。请稍后重试");
        }
        JSONObject response = json.getJSONObject("message");
        JSONObject requestbody = json.getJSONObject("request");
       if ((int)json.get("code") == 200 && "ACCEPTED".equals(response.getString("batchStatus"))) {
            logger.info("提现成功");
            userInfoBO.setAmount(userInfoBO.getAmount().subtract(reqData.getAmount()));
            this.setModifiedData(sign,userInfoBO);
            userService.update(userInfoBO);
           // 保存提现记录
            savePayment(sign,reqData,response, requestbody,userInfoBO);

        } else {
            logger.info("提现异常===="+resData);
            throw new MallException("提现异常");
        }

        return respSign;
    }

    public void sendFailMessage(UserInfoBO userInfoBO,UserInfoBO reqData){
        //查询管理员
        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("role",2);
        List<UserInfoBO> userList = userService.list(paramsBuilder.build());

        if(!userList.isEmpty()) {

            ParamsBuilder name1 = ParamsBuilder.newBuild()
                    .addParam("value",userInfoBO.getRealName());
            ParamsBuilder time2 = ParamsBuilder.newBuild()
                    .addParam("value", DateUtil.dateToString(new Date(),"yyyy年MM月dd日 HH:mm"));
            ParamsBuilder amount3 = ParamsBuilder.newBuild()
                    .addParam("value",reqData.getAmount().intValue()+"元");
            ParamsBuilder thing5 = ParamsBuilder.newBuild()
                    .addParam("value","提现失败，请检查资金是否充足");

            ParamsBuilder data = ParamsBuilder.newBuild()
                    .addParam("name1",name1.build())
                    .addParam("time2",time2.build())
                    .addParam("amount3",amount3.build())
                    .addParam("thing5",thing5.build());

            ParamsBuilder params = ParamsBuilder.newBuild()
                    .addParam("template_id", WxConstants.USER_GET_MONEY_FAIL)
                    .addParam("data",data.build());

            for (UserInfoBO userInfo : userList) {
                    params.addParam("touser", userInfo.getWxOpenId());
                    String resData = HttpUtil.post(WxConstants.SEND_MESSAGE, JSON.toJSONString(params.build()));
                    JSONObject param = JSON.parseObject(resData);
                    logger.info(param.toString());

            }


        }

    }
    public void sendSucessMessage(UserInfoBO userInfoBO,PayPaymentBO paymentBO){
        //查询管理员
        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("role",2);
        List<UserInfoBO> userList = userService.list(paramsBuilder.build());

        if(!userList.isEmpty()) {

            ParamsBuilder name1 = ParamsBuilder.newBuild()
                    .addParam("value",userInfoBO.getRealName());
            ParamsBuilder time2 = ParamsBuilder.newBuild()
                    .addParam("value", DateUtil.dateToString(paymentBO.getCreatedDate(),"yyyy年MM月dd日 HH:mm"));
            ParamsBuilder amount3 = ParamsBuilder.newBuild()
                    .addParam("value",paymentBO.getAmount().intValue()+"元");
            ParamsBuilder character_string4 = ParamsBuilder.newBuild()
                    .addParam("value",paymentBO.getPayNo());

            ParamsBuilder data = ParamsBuilder.newBuild()
                    .addParam("name1",name1.build())
                    .addParam("time2",time2.build())
                    .addParam("amount3",amount3.build())
                    .addParam("character_string4",character_string4.build());

            ParamsBuilder params = ParamsBuilder.newBuild()
                    .addParam("template_id", WxConstants.USER_GET_MONEY_SUCCESS)
                    .addParam("data",data.build());

            for (UserInfoBO userInfo : userList) {
                params.addParam("touser", userInfo.getWxOpenId());
                String resData = HttpUtil.post(WxConstants.SEND_MESSAGE, JSON.toJSONString(params.build()));
                JSONObject param = JSON.parseObject(resData);
                logger.info(param.toString());

            }


        }

    }



    private void savePayment(CmdSign sign,UserInfoBO reqData , JSONObject response,JSONObject request,UserInfoBO userInfoBO) {
        PayPaymentBO payPaymentBO = new PayPaymentBO();
        payPaymentBO.setUserId(reqData.getUserId());
        payPaymentBO.setPayNo(request.getString("outBatchNo"));
        payPaymentBO.setAmount(reqData.getAmount());
        payPaymentBO.setPayType("1");
        payPaymentBO.setBatchId(response.getString("batchId"));
        payPaymentBO.setPayDate(new Date());
        payPaymentBO.setRemark("提现");
        payPaymentBO.setReqData(request.toString());
        payPaymentBO.setSyncData(response.toString());
        payPaymentBO.setStatus(OrdersItemStatusEnum.SUCCESS.getStatus());
        this.setCreatedData(sign,payPaymentBO);
        this.payPaymentService.post(payPaymentBO);

        //发送提现成功通知
        sendSucessMessage(userInfoBO,payPaymentBO);
    }

    @Override
    public boolean anon(CmdSign sign) {
        return true;
    }

    @Override
    public CmdSign verify(HttpServletRequest request, CmdSign sign) throws Exception {
        UserInfoBO reqData = super.getData(sign, UserInfoBO.class);
        String openId = request.getHeader(WxConstants.X_WX_OPENID);
        if (StringUtils.isBlank(openId)) {
            throw new MallException("请求异常,header未发现openID");
        }

        if (StringUtils.isBlank(reqData.getUserId())) {
            throw new MallException("用户id不能为空");
        }
        if (Objects.isNull(reqData.getAmount())) {
            throw new MallException("提现金额不能为空");
        }

        return null;
    }

    @Override
    public String getCmdCode() {
        return UserCmdCode.USER_GET_MONEY;
    }

    @Autowired
    private IPayPaymentService payPaymentService;

    @Autowired
    private IUserInfoService userService;
}